<template>
  <div>
    <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px;">
      <el-form-item label="组织ID">
        <el-input v-model="searchForm.orgId" placeholder="请输入组织ID" clearable />
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="searchForm.keywords" placeholder="请输入公告关键字" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="notices" style="width: 100%">
      <el-table-column prop="id" label="公告ID" width="90" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column prop="orgId" label="组织ID" width="100" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button size="small" @click="goDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const searchForm = ref({
  orgId: '',
  keywords: ''
})
const notices = ref([])

// 搜索组织公告
const handleSearch = async () => {
  // 优先按组织ID查找所有公告
  if (searchForm.value.orgId) {
    try {
      const res = await axios.get(`http://localhost:8080/student/${searchForm.value.orgId}/informs`)
      if (res.data && res.data.code === 200) {
        notices.value = res.data.data || []
      } else {
        notices.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '未找到该组织公告')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
      return
    }
  }
  // 按关键字查找公告
  if (searchForm.value.keywords) {
    try {
      const res = await axios.get(`http://localhost:8080/student/${searchForm.value.keywords}/announcements/searchByKeywords`)
      if (res.data && res.data.code === 200) {
        notices.value = res.data.data || []
      } else {
        notices.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '未找到相关公告')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
      return
    }
  }
  // 如果都没填，清空
  notices.value = []
}

// 重置
const resetSearch = () => {
  searchForm.value.orgId = ''
  searchForm.value.keywords = ''
  notices.value = []
}

const goDetail = (row) => {
  // 跳转到公告详情页
  router.push({ name: 'StuNoticeDetail', params: { id: row.id } })
}
</script>